package org.mcjug.locationmailer.receiver;


import org.mcjug.locationmailer.LocationMailerApplication;
import org.mcjug.locationmailer.R;
import org.mcjug.locationmailer.activity.LocationMailerActivity;
import org.mcjug.locationmailer.activity.SignInActivity;
import org.mcjug.locationmailer.util.ParcelableException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
//import android.util.Log;

public class ExceptionBroadcastReceiver extends BroadcastReceiver {
	private static final String TAG = SignInActivity.class.getSimpleName();
	public static final String EXCEPTION = "exception";
	
    @Override
    public void onReceive(Context context, Intent intent) {
       if (intent.getAction().equals(context.getString(R.string.intentExceptionActionName))) {
            ParcelableException parcelableException = intent.getParcelableExtra(EXCEPTION);
            
            //Log.e(TAG, "Error caught by ExceptionBroadcastReciever", parcelableException);
            
    		Context applicationContext = context.getApplicationContext();    	 	
    		LocationMailerApplication locationMailerApp = (LocationMailerApplication)applicationContext;
            Intent exceptionIntent;
               		
    		if (locationMailerApp.isActivityRunning()) {
	            exceptionIntent = new Intent(context.getString(R.string.intentDisplayExceptionActionName));
				exceptionIntent.putExtra(EXCEPTION, (Parcelable)parcelableException);
	            context.sendBroadcast(exceptionIntent);
           } else {
	        	exceptionIntent = new Intent(applicationContext, LocationMailerActivity.class);
	        	exceptionIntent.putExtra(EXCEPTION, (Parcelable)parcelableException);
	        	exceptionIntent.setAction(context.getString(R.string.intentDisplayExceptionActionName));
	        	
				PendingIntent pendingIntent = PendingIntent.getActivity(
						applicationContext, -1, exceptionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

				NotificationManager notificationManager = 
					(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
				Notification notification = new Notification(android.R.drawable.ic_dialog_info, "", 0);
	    		notification.when = System.currentTimeMillis();
	    		notification.flags |= Notification.FLAG_AUTO_CANCEL;

	    		CharSequence notificationTitle = context.getText(R.string.exceptionNotificationTitle);
	    		CharSequence notificationSummary = context.getString(R.string.exceptionNotificationSummary);

	    		notification.setLatestEventInfo(applicationContext,
	    				notificationTitle, notificationSummary, pendingIntent);
	    		notificationManager.notify(0, notification);	        	
	        }
        } 
    }
}
